using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace array_demo.Model
{
    public class LinkedList2<E>
    {
        /// <summary>
        /// 定义节点对象
        /// </summary>
        private class Node
        {
            // 当前的元素
            public E e;

            // 当前指向下一个节点的引用
            public Node next;

            /// <summary>
            ///初始化构造函数
            /// </summary>
            /// <param name="e"></param>
            /// <param name="next"></param>
            public Node(E e, Node next)
            {
                this.e = e;
                this.next = next;
            }

            /// <summary>
            /// 初始化构造函数 不指定下一级别
            /// </summary>
            /// <param name="e"></param>
            public Node(E e)
            {
                this.e = e;
                this.next = null;
            }

            public override string ToString()
            {
                return e.ToString();
            }
        }

        /// <summary>
        /// 头结点
        /// </summary>
        private Node head;

        /// <summary>
        /// 尾指针
        /// </summary>
        private Node tail;

        /// <summary>
        /// 链表中的元素个数
        /// </summary>
        private int N;

        public LinkedList2()
        {
            tail = null;
            head = null;
            N = 0;

        }

        public int count
        {
            get { return N; }
        }

        public bool isEmpty
        {
            get { return N == 0; }
        }

        public void AddLast(E e)
        {
            Node node = new Node(e);
            if (isEmpty)
            {
                head = node;
                tail = node;
            }
            else
            {
                tail.next = node;
                tail = node;
            }
            N++;
        }

        public E DeleteFirst()
        {
            if (isEmpty)
                throw new AggregateException("数组索引越界");
            E e = head.e;
            head = head.next;
            N--;

            if (head == null)
                tail = null;

            return e;
        }

        public E GetFirst()
        {
            if (isEmpty)
                throw new AggregateException("链表为空");
            return head.e;
        }


        /// <summary>
        /// 重写转字符串
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder stringBuilder = new StringBuilder();
            Node curr = head;
            while (curr != null)
            {
                stringBuilder.Append(curr + "->");
                curr = curr.next;
            }
            stringBuilder.Append("null");
            return stringBuilder.ToString();
        }
    }
}